<script setup>
import {onBeforeUnmount, ref, shallowRef, onMounted, toRaw, nextTick} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {DomEditor} from "@wangeditor/editor";
import {BASE_URL} from "../config/index.js";

// 定义 props
const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    },
    minHeight:{
        type:Number,
        default:200
    }
})
// 定义 emit
const emit = defineEmits(['update:modelValue'])



// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
//toolbar实例
const toolbar = ref({})
const EditorStyle = {
    minHeight: `${props.minHeight}px`,
    overflowY: 'hidden'
}

// 内容 HTML
const valueHtml = ref(props.modelValue)

const toolbarConfig = {
    excludeKeys:[
        "todo","clearStyle","insertVideo","redo","header3","blockquote",
        "justifyLeft","justifyRight","justifyCenter","italic","bgColor","|"
    ]
}
const editorConfig = {
    MENU_CONF: {},
    placeholder: '请输入内容...',
}

editorConfig.MENU_CONF['uploadImage'] = {
    server: BASE_URL + '/files/upload',
    fieldName:'file',
    allowedFileTypes: ['image/*'],
    withCredentials: true,
    maxFileSize: 10 * 1024 * 1024, // 10M
    base64LimitSize: 7 * 1024, // 7kb
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor
    let config = editorRef.value.getConfig()

    nextTick(() => {
        toolbar.value = DomEditor.getToolbar(editor)
        const curToolbarConfig = toolbar.value.getConfig()
    })
}

const handleChange = (newHtml) => {
    valueHtml.value = newHtml.getHtml()
    emit('update:modelValue', newHtml.getHtml()) // 通知父组件数据变化
}

onMounted(() => {

})

const updateViews = () => {
    editorRef.value.updateView()
}
const getHtml = () => {
    editorRef.value.getHtml()
}
const setEditorHtml = (html) => {
    editorRef.value.setHtml(html)
}
//导出updateViews
defineExpose({updateViews,setEditorHtml,getHtml})

</script>

<template>
    <div style="border: 1px solid #ccc">
        <Toolbar
            style="border-bottom: 1px solid #ccc;width: 100%;"
            :editor="editorRef"
            mode="simple"
            :defaultConfig="toolbarConfig"
        />
        <Editor
            :style="EditorStyle"
            v-model="valueHtml"
            mode="simple"
            :defaultConfig="editorConfig"
            @onCreated="handleCreated"
            @onChange="handleChange"
        />
    </div>
</template>

<style scoped>

</style>
